package com.example.init;

import com.example.util.PropertiesUtil;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;

public class ServerInit {

    private static int port = 8080;

    private static final String portPrefix = "--server.port";

    public static void init(HttpServer server,String packageName,String[] args){
        try {
            server.bind(new InetSocketAddress(getPort(args)),0);
            HttpContextInit.init(server, packageName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static int getPort(String[] args){
        String portString = null;
        if(args != null){
            for(String arg:args){
                if(arg.startsWith(portPrefix)){
                    String[] array = arg.split("=");
                    if(array[1].isEmpty()){
                        throw new RuntimeException("未指定正确的--server.port");
                    }
                    portString = array[1];
                    break;
                }
            }
        }
        if(portString != null){
            port = Integer.parseInt(portString);
        }else {
            portString = PropertiesUtil.getProperty("server.port");
        }
        if(portString != null){
            port = Integer.parseInt(portString);
        }
        return port;
    }
}
